<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/17
 * Time: 11:28
 */

namespace app\api\controller\v1;



use app\api\controller\BaseController;
use app\api\service\Token;
use app\api\validate\ClassPagingParameter;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\OrderPalace;
use \app\api\service\Order as OrderService;
use \app\api\model\Order as OrderModel;
use app\api\validate\PagingParameter;
use app\lib\exception\OrderException;
use app\lib\exception\SuccessMessage;
use think\paginator;

class Order extends BaseController
{
    //1.用户在选着商品时，向API提交包含他所选商品的相关信息
    //2.API在接收到信息后，需要检查商品的库储量
    //3.有库存，把订单数据存入存入数据库中 = 下单成功了，返回客户端信息，告诉客户可以支付了
    //4.调用支付接口，进行支付
    //5.还需进行库存量检查
    //6.服务器调用微信支付接口进行支付
    //7.微信返回一个支付结果
    //8.支付成功还需进行库存量检查
    //9.成功：减少库存量
    /**
     * 方法名全部小写，不支持驼峰（thinkphp5 真尼玛坑）
     * @var array
     */
    protected $beforeActionList=[
        'checkExclusiveScope' => ['only'=>'palaceOrder,cancelOrder'],
       'checkPrimaryScope' => ['only'=>'getSummary,getOrderDetail,getSummaryByUser,getSummaryByClass'],
    ];
    /**
     * 用户下单
     * @return array
     */
    public function palaceOrder(){
        (new OrderPalace())->goCheck();
        $data = input('post.w_id');
        $array = explode('_',$data);
        $w_id = $array[1];
        $products = input('post.products/a');
        $uid = Token::getCurrentUid();
        $t_id = Token::getCurrentTokenVar('manager_id');
        $order = new OrderService();
        $orderInfo = $order->place($uid,$w_id,$t_id,$products);
        return json($orderInfo);
    }
    /**
     * 用户取消订单
     * @param $id
     * @return \think\response\Json
     */
    public function cancelOrder($id){
        (new IDMustBePositiveInt())->goCheck();
        $order = new OrderService();
        $uid = Token::getCurrentUid();
        $status =  $order->closeTrade($id,$uid);
        if (!$status){
            return  json( new SuccessMessage());
        }
    }

    /**
     * 用户确认订单
     * @param $id
     * @return \think\response\Json
     */
    public function confirmOrder($id){

        (new IDMustBePositiveInt())->goCheck();
        $order = new OrderService();
        $uid = Token::getCurrentUid();
        $status =  $order->confirmTrade($id,$uid);
        if (!$status){
            return  json( new SuccessMessage());
        }
    }
    /**
     * 获取用户订单列表
     * @param int $page
     * @param int $size
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getSummaryByUser($status=100,$page=1,$size=15){
        (new ClassPagingParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $paginate = OrderModel::getOrderByUserID($uid,$status,$page,$size);
        if ($paginate->isEmpty()){
            $result = [
                'data'=>[],
               'current_page'=>$paginate->getCurrentPage()
           ];
        }else{
            $data = $paginate->hidden(['snap_items','snap_address','prepay_id'])->toArray();
            $result =  [
                'data'=>$data,
                'current_page'=>$paginate->getCurrentPage()
            ];
        }
        return json($result);
    }
    /**
     * 管理员获取商品
     * @param int $page
     * @param int $size
     * @return \think\response\Json
     */
    public function getSummary($status=100,$page=1,$size=15){
        (new PagingParameter())->goCheck();
        $t_id = Token::getCurrentUid();
        $paginate = OrderModel::getOrderByManager($status,$t_id,$page,$size);
        if ($paginate->isEmpty()){
            $data = $paginate;
        }else {
            $data = $paginate->hidden(['snap_items', 'snap_address', 'prepay_id'])->toArray();
        }
        return json($data);
    }
    /**
     * 获取订单详情
     * @param $id
     * @return $this
     * @throws OrderException
     */
    public function getOrderDetail($id){
        (new IDMustBePositiveInt())->goCheck();
        $orderInfo = OrderModel::getOrderInfoByID($id);
        if (!$orderInfo){
            throw  new OrderException();
        }
        return $orderInfo->hidden(['prepay_id']);
    }
    /**
     * 发送模板消息，通知用户
     * @param $id
     * @return SuccessMessage
     */
    public function delivery($id,$data){
        //(new IDMustBePositiveInt())->goCheck();
        $t_id = Token::getCurrentUid();
        $order = new OrderService();
        $success = $order->delivery($t_id,$id,$data);
      if ($success){
          return  json( new SuccessMessage());
      }
    }

    /**
     * 获取用户分类订单列表
     * @param $status
     * @return OrderException|false|\PDOStatement|string|\think\Collection
     */
    public function getSummaryByClass($status,$page=1,$size=15){
        (new ClassPagingParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $paginate =  OrderModel::getOrderByClass($uid,$status,$page,$size);
        if ($paginate->isEmpty()){
            $data = $paginate;
        }else {
            $data = $paginate->hidden(['snap_items', 'snap_address', 'prepay_id'])->toArray();
        }
        return json($data);
    }



    /**
     * 获取总订单信息
     * @param $time
     * @return string
     */
    public function getAllOrders($time){
        $t_id = Token::getCurrentTokenVar('t_id');
        $service = new OrderService();
        $result =  $service->getAllOrders($t_id,$time);
        if (!empty($result)){
            $data['code'] = 200;
            $data['content'] = $result;
        }else{
            $data['code'] = 2002;
            $data['content'] = '';
        }
        return json_encode($data);
    }
    /**
     *查询订单
     * @param $status
     * @return OrderException|false|\PDOStatement|string|\think\Collection
     */
    public function searchOrder($condition,$page=1,$size=15){
        $uid = Token::getCurrentUid();
        $paginate =  OrderModel::searchOrder($condition,$uid,$page,$size);
        if ($paginate->isEmpty()){
            $data = $paginate;
        }else {
            $data = $paginate->hidden(['snap_items', 'snap_address', 'prepay_id'])->toArray();
        }
        return json($data);
    }


}